<template>
  <div id="login">
    <span class="msg">登录</span>
    <div class="title">校园社区</div>
   
    <!-- 登录表单 -->
    <!-- 用户名登录 -->
    <van-form @submit="onSubmit" ref="login" id="loginForm" validate-trigger="onBlur">
    <!-- 登录切换按钮 -->
    <switch-button :ButtonName="switchName" @change="changeMode(index)" id="switch"></switch-button>
      <van-cell-group inset class="formItem" v-show="mode == 'username'">
        <van-field
          v-model="username"
          name="username"
          label="用户名"
          placeholder="请输入用户名"
          left-icon="user-o"
          label-width="1.9rem"
          :rules="[{ required: mode == 'username', message: '请填写用户名' }]"
        />
      </van-cell-group>
      <van-cell-group inset class="formItem" v-show="mode == 'username'">
        <van-field
          v-model="password"
          type="password"
          name="password"
          label="密码"
          placeholder="请输入密码"
          left-icon="edit"
          label-width="1.9rem"
          :rules="[{ required: mode == 'username', message: '请填写密码' }]"
        />
      </van-cell-group>
      <!-- 手机验证码登录 -->
      <van-cell-group inset class="formItem" v-show="mode == 'phone'">
        <van-field
          v-model="phone"
          name="phone"
          label="电话号码"
          label-width="1.9rem"
          placeholder="请输入电话号码"
          left-icon="phone-o"
          :rules="[{ validator:phoneValidator, message: '请填写电话号码' }]"
        />
      </van-cell-group>
      <van-cell-group inset class="formItem" v-show="mode == 'phone'">
        <van-field
          v-model="vcode"
          center
          clearable
          label="短信验证码"
          label-width="1.9rem"
          left-icon="comment-o"
          placeholder="请输入验证码"
          :rules="[{ required: mode == 'phone', message: '请输入验证码' }]"
        >
          <template #button>
            <van-button
              size="small"
              type="primary"
              :disabled="!phone || verfied.isSend || !canSend"
              @click="sendVerfiyCode"
              >{{ verfied.vbtnMessage }}</van-button
            >
          </template>
        </van-field>
      </van-cell-group>
      <div style="margin: 16px">
        <van-button
          round
          block
          type="primary"
          color="linear-gradient(to right, #1989fa, #4ea9f7)"
          native-type="submit"
        >
          登录
        </van-button>
      </div>
      <div class="fnArea">
        <span id="forget" @click="gotoForget">找回密码</span>
        <span id="register" @click="gotoRegiser">快速注册</span>
        <span id="visitor" @click="visitorLogin">游客登录</span>
      </div>
    </van-form>
  </div>
</template>
<script>
import { Form, Field, Button, Icon, CellGroup, Toast, Image } from "vant";
import { loginByUsername } from "@/api/UserBaseAPI/login.js";
import { VerfyingCode ,sendVerfiedCode} from "@/utils/verifyCode.js";
import { mapMutations } from "vuex";
import {isRegisted} from "@/api/UserBaseAPI/register.js"
import {cancelPromise} from "@/utils/cancelPromise.js"
import {saveLoginStatus,loginByVisitor} from "@/utils/loginStatus.js"
import switchButton from "@/components/Common/SwitchButton.vue"
export default {
  name: "login",
  data() {
    return {
      username: "",
      password: "",
      phone: "",
      //验证码
      vcode: "",
      //登录模式
      mode: "username",
      //发送验证码按钮
      verfied: {
        isSend: false,
        vbtnMessage: "发送验证码",
        vtime: 0,
      },
      canSend: false,
      switchName:["用户名","手机号"],
    };
  },
  methods: {
    //发送验证码
    sendVerfiyCode() {
      this.verfied.phone = this.phone;
      //封装发送验证码功能util
      sendVerfiedCode.call(this.verfied);
    },
    //改变登录模式
    changeMode(index) {
      switch (index) {
        //0代表用户名登录模式
        case 0:
          this.mode = "username";
          break;
        //1代表手机号登录模式 
        case 1:
          this.mode = "phone";
          break;
      }
      this.resetForm();
    },
    gotoRegiser() {
      this.$router.push("/register");
    },
    gotoForget(){
      this.$router.push("/forget");
    },
    //手机号校验规则
    phoneValidator() {
      if (this.mode == "phone") {
        let phone = this.phone;
        return cancelPromise.request("loginPhone", isRegisted({ type: "phone", verfieditem: phone })
          .then((res) => {
            if (!res.isRegisted) {
              this.canSend = false;
              return "该手机号未注册账号";
            } else {
              this.canSend = true;
            }
          })
          .catch((err) => {
            Toast.fail({
              duration: 1000,
              orbidClick: true,
              message: err,
            });
            this.canSend = false;
          }))
        
      }
    },
    //登录
    async onSubmit() {
      let res;
      if (this.mode == "username") {
        res = await loginByUsername({
          username: this.username,
          password: this.password,
        });
      } else {
        res = await VerfyingCode(this.phone, this.vcode);
      }
      if (res && res.success) {
        let college = res.userInfo.college || res.college
        let status = res.userInfo.status
        saveLoginStatus(res.userInfo.username,college,status)
        let msg = status == 0?"未审核用户":status==-1?"被屏蔽用户":""
        Toast.success({
          duration: 1500,
          message: "登录成功\n"+msg,
          forbidClick: true,
          onClose: () => {
            this.$router.replace("/");
          },
        });
        res.userInfo.college = res.college;
        this.setUserInfo(res.userInfo);
        // username存储到sessionstorage中     
      } else {
        Toast.fail({
          duration: 1500,
          message: res.message,
        });
      }
    },
    //重置
    resetForm() {
      this.username = this.password = this.phone = this.vcode = "";
      this.$refs.login.resetValidation();
    },
    //游客登录
    visitorLogin(){
      loginByVisitor();
      Toast.fail({
          duration: 1500,
          message: "游客登录受限哦！",
          forbidClick: true,
          onClose: () => {
            this.$router.replace("/");
          },
      });
    },
    ...mapMutations(["setUserInfo"]),
  },
  components: {
    [Form.name]: Form,
    [CellGroup.name]: CellGroup,
    [Field.name]: Field,
    [Button.name]: Button,
    [Icon.name]: Icon,
    [Toast.name]: Toast,
    [Image.name]: Image,
    [Toast.name]: Toast,
    switchButton
  },
  mounted(){
    //document.querySelector("#login").style.height = window.innerHeight+'px';
  },
};
</script>

<style lang="less" scoped>
#login {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  height: 100vh;
  background-image: url("../../assets/login_bgc.jpg");
  background-size: cover;
  background-position: center;
}
#loginForm {
  position: absolute;
  top: 53%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 360px;
  height: 150px;
  padding: 30px 0;
  color: rgb(240, 240, 240);
}
.msg {
  position: absolute;
  top: 40px;
  left: 20px;
  font-size: 26px;
  font-weight: bolder;
  text-align: left;
  letter-spacing: 2px;
}
.msg::after {
  content: "欢迎再次回来~";
  display: block;
  font-size: 16px;
  font-weight: normal;
  color: #6d6c6c;
  letter-spacing: 0px;
}
.title {
  position: absolute;
  top: 23%;
  left: 8%;
  font-size: 42px;
  font-weight: bolder;
  letter-spacing: 1px;
}
.formItem {
  margin-top: 12px;
  border-radius: 18px;
  border: 1px solid #ccc;
}
.fnArea {
  width: 300px;
  height: 20px;
  margin: 0 auto;
  font-size: 16px;
  font-weight: bold;
  letter-spacing: 1px;
  overflow: hidden;
  #forget {
    position: absolute;
    left: 20px;
    color: black;
  }
  #register {
    position: absolute;
    right: 20px;
    color: #00baeb;
  }
  #visitor{
    position: absolute;
    margin-top:30px;
    right: 20px;
    color: #1989fa;
  }
}
#switch{
  position: absolute;
  top: 9px;
  right: 7%;
}
</style>